package com.atguigu.exam;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * 编写一个服务器和一个客户端
 1)服务器上保存了几个用户名和对应的密码;且能验证客户端发送过来的用户名和密码,是否和保存的某个用户名和对应的密码一致.
 2)客户端能连接到服务器，并把用户在键盘上输入的用户名和密码，发送到服务器上
 * @author xbd
 * @create 2021-05-31 19:06
 */
public class UsePasswordTest {
    public void connServer(){
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 8899);
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String name = scanner.next();
            System.out.println("请输入密码：");
            String password = scanner.next();
            String uesr = name + "," + password;

            os = socket.getOutputStream();
            os.write(uesr.getBytes());
            socket.shutdownOutput();

            is = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            System.out.println(br.readLine());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public static void main(String[] args) {
        new UsePasswordTest().connServer();
    }
}
